//
//  AppDelegateAttachment.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-29.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "AppDelegateAttachment.h"

@implementation AppDelegateAttachment
/**
 创建本地缓存路径
 */
-(void)createLocalDirectory{
    
    [NSThread detachNewThreadSelector:@selector(createLocalDirectoryThread) toTarget:self withObject:nil];
    
}
-(void)createLocalDirectoryThread{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *path=[CommonConfigUtil getImageLocalPath];
    BOOL isDir;
    if(![fileManager fileExistsAtPath:path isDirectory:&isDir]){
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *filestorePath=[CommonConfigUtil getFileLocalPath];
    if(![fileManager fileExistsAtPath:filestorePath isDirectory:&isDir]){
        [fileManager createDirectoryAtPath:filestorePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
}

-(void)registerForRemoteNotification{
    
    [NSThread detachNewThreadSelector:@selector(registerForRemoteNotificationThread) toTarget:self withObject:@"N"];
}
-(void)registerForRemoteNotificationThread{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
/**
 友盟初始化
 */
-(void)umengStartup{
    [MobClick startWithAppkey:[CommonConfigUtil getUmengAppKey] reportPolicy:REALTIME channelId:[CommonConfigUtil getChannelId]];
}
- (void)addMobileUser{
    [NSThread detachNewThreadSelector:@selector(addMobileUserThread:) toTarget:self withObject:@"N"];
}
- (void)addMobileUserThread:(NSString *)isSleep{
    
    NSUserDefaults* myDefaults=[NSUserDefaults standardUserDefaults];
    if(nil!=isSleep && [@"Y" isEqualToString:isSleep]){
        [NSThread sleepForTimeInterval:5];
    }
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if(nil==openUDID||[@"" isEqualToString:openUDID]){
        return;
    }
    
    NSString *deviceInfo= [CommonConfigUtil getDeviceInfo];
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/saveMobileuser/?type=%@&uuid=%@&appversion=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID,[CommonConfigUtil getMobileClientApp]];
    
    
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=deviceInfo&&![@"" isEqualToString:deviceInfo]){
        [url appendString:deviceInfo];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    if(nil!=reData && [reData length]>0){
        NSError *error=nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        //NSDictionary *dictionary=[[CJSONDeserializer deserializer] deserializeAsDictionary:reData error:&error];
        
        if(!error){
            NSString  *taobosid=[dictionary objectForKey:@"sid"];//toabosid
            if(nil!=taobosid && ![@"" isEqualToString:taobosid]){
                [myDefaults setObject:taobosid forKey:@"taobosid"];
                [myDefaults synchronize];
            }
            
        }
    }
    
    
    reData=nil;
    
    
}
/**
 处理加载消息
 */
-(void)parseLaunchingOptions:(NSDictionary *)launchOptions
{
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    NSDictionary *payload=[launchOptions  objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(nil!=payload){
        NSDictionary *aps=[payload objectForKey:@"aps"];
        NSString *alertMessage=[aps objectForKey:@"alert"];
        if(nil==alertMessage){
            alertMessage=@"" ;
        }
        
        NSString *advtype =[payload objectForKey:@"t"];//advtype
        NSString *objectid =[payload objectForKey:@"i"];
        NSString *objectname =[payload objectForKey:@"n"];
        NSString *batchId =[payload objectForKey:@"b"];//批量
        
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
        if(nil==batchId)batchId=@"";
        
        NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
        
        
        if([@"10" isEqualToString:advtype] || [advtype intValue]==10){//评分
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                  // message:@"亲，喜欢我就给我个评分吧，您的评价真得很重要！"
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"残忍拒绝"
                                                  otherButtonTitles:@"仁慈给予",nil];
            [alert setTag:998];
            [alert show];
            
        }
        else  if([@"11" isEqualToString:advtype] || [advtype intValue]==11){//分享
            /*
             UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
             //message:@"亲，喜欢我就与朋友们分享吧！"
             message:alertMessage
             delegate:self
             cancelButtonTitle:@"残忍拒绝"
             otherButtonTitles:@"仁慈给予",nil];
             [alert setTag:999];
             [alert show]; */
            
        }
        else {
            [self pushMessageWithParams:params];
        }
        
        
        [NSThread detachNewThreadSelector:@selector(savePushMsgLog:) toTarget:self withObject:params];
        
    }
    
}
-(void)pushMessageWithParams:(NSDictionary *)params{
    NSString *advid=[params objectForKey:@"advid" ];
    NSString *advtype=[params objectForKey:@"advtype" ];
    //  NSString *name=[params objectForKey:@"name" ];
    NSString *objectId=[params objectForKey:@"objectId" ];
    NSString *objectName=[params objectForKey:@"objectName" ];
    NSString *urlparams=[params objectForKey:@"urlparams" ];
    
    
    
    if(nil!=advid && ![@"" isEqualToString:advid]){
        
        NSDictionary *statParms =[NSDictionary dictionaryWithObjectsAndKeys:advid,@"objectid",@"ad",@"page",nil];
        [NSThread detachNewThreadSelector:@selector(saveMobileStat:) toTarget:self withObject:statParms];
    }
    
    
    NSLog(@"advtype==%@",advtype);
    //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
    
    if([@"0" isEqualToString:advtype] || [advtype intValue]==0 ){
        
        
    }
    else  if([@"1" isEqualToString:advtype] || [advtype intValue]==1 ){
        
    }
    else  if([@"2" isEqualToString:advtype] || [advtype intValue]==2 ){
        
        
        
        
    }
    else  if([@"3" isEqualToString:advtype] || [advtype intValue]==3 ){
        
        
    }
    else  if([@"4" isEqualToString:advtype] || [advtype intValue]==4 ){
        
        
    }
    else  if([@"5" isEqualToString:advtype] || [advtype intValue]==5 ){
        
        
    }else  if([@"8" isEqualToString:advtype] || [advtype intValue]==8 ){
        
        
        NSString *appName=@"";
        if(nil!=urlparams && ![@"" isEqualToString:urlparams] ){
            NSArray *paramsArray=[urlparams componentsSeparatedByString:@"appname="];
            if(nil!=paramsArray &&  [paramsArray count]>1 ){
                appName= [paramsArray objectAtIndex:1 ];
            }
            
        }
        
        if(nil==appName)appName=@"";
        
        if(![@"" isEqualToString:appName] && [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:appName]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appName]];
        }
        else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
        
    }
    else  if([@"9" isEqualToString:advtype] || [advtype intValue]==9 ){
        
        //start with app:
        if ([objectName hasPrefix:@"app:"]){
            //[self advAppUrlParseWithAppUrl:objectName withUrlparams:urlparams withUINavigationController:navigationController];
        }
        else if(nil!=objectId && ([@"1" isEqualToString:objectId] || [objectId intValue]==1)  ) {
            
            
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
            
        }
        else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
    }
    
    
}
-(void)savePushMsgLog:(NSDictionary *)params{
       [NSThread detachNewThreadSelector:@selector(savePushMsgLogThread:) toTarget:self withObject:params];
}
//save push message log
-(void)savePushMsgLogThread:(NSDictionary *)params{
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    
    
    
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    if(nil==openUDID){
        openUDID=@"";
    }
    
    NSUserDefaults* myDefaults=[NSUserDefaults standardUserDefaults];
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/plus/saveDetailLog/?mobiletype=%@&uuid=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID];
    
    
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[params objectForKey:@"advtype"]&&![@"" isEqualToString:[params objectForKey:@"advtype"]]){
        [url appendFormat:@"&advtype=%@",[params objectForKey:@"advtype"]];
    }
    
    if(nil!=[params objectForKey:@"objectId"]&&![@"" isEqualToString:[params objectForKey:@"objectId"]]){
        [url appendFormat:@"&objectid=%@",[params objectForKey:@"objectId"]];
    }
    if(nil!=[params objectForKey:@"objectName"]&&![@"" isEqualToString:[params objectForKey:@"objectName"]]){
        [url appendFormat:@"&objectname=%@",[[params objectForKey:@"objectName"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"title"]&&![@"" isEqualToString:[params objectForKey:@"title"]]){
        [url appendFormat:@"&title=%@",[[params objectForKey:@"title"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"batchid"]&&![@"" isEqualToString:[params objectForKey:@"batchid"]]){
        [url appendFormat:@"&batchid=%@",[params objectForKey:@"batchid"]];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    
    reData=nil;
    
    
    
    
    
}



@end
